﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Contacts.Maui.Views_MVVM;
using Contacts.UseCases.Interfaces;
using System.Collections.ObjectModel;
using ContactCoreBusiness = Contacts.CoreBusiness.Contact;

namespace Contacts.Maui.ViewModels
{
    public partial class ContactsViewModel : ObservableObject
    {
        private readonly IViewContactsUseCases ViewContactsUseCases;
        private readonly IDeleteContactUseCase deleteContactUseCase;

        public ObservableCollection<ContactCoreBusiness> Contacts { get; set; }

        private string filterText;

        public string FilterText
        {
            get { return filterText; }
            set
            {
                filterText = value;
                LoadContactAsync(filterText);
            }
        }

        public ContactsViewModel(IViewContactsUseCases ViewContactsUseCases, IDeleteContactUseCase DeleteContactUseCase)
        {
            this.ViewContactsUseCases = ViewContactsUseCases;
            this.deleteContactUseCase = DeleteContactUseCase;
            this.Contacts = new ObservableCollection<ContactCoreBusiness>();
        }

        public async Task LoadContactAsync(string filterText = null)
        {
            this.Contacts.Clear();
            var contacts = await this.ViewContactsUseCases.ExecuteAsync(filterText);
            if (contacts != null && contacts.Count > 0)
            {
                foreach (var contact in contacts)
                {
                    this.Contacts.Add(contact);
                }
            }
        }

        [RelayCommand]
        public async Task DeleteContact(int ContactId)
        {
            await this.deleteContactUseCase.ExecuteAsync(ContactId);
            await this.LoadContactAsync();
        }

        [RelayCommand]
        public async Task GoToAddContact()
        {
            await Shell.Current.GoToAsync(nameof(AddContactPage_MVVM));
        }

        [RelayCommand]
        public async Task GoToEditContact(int ContactId)
        {
            await Shell.Current.GoToAsync($"{nameof(EditContactPage_MVVM)}?Id={ContactId}");
        }
    }
}
